const request = require('request');
const moment = require('moment');
const partner_code = 'EWEC';
const credential_code = 'vG9kuvOV6Spn8urbhUCSG8HWY6fMot6x';
const nonce_str = 'q1231231221asdasd';
const crypto = require('crypto');

function generate_sign(time_stamp) {
  var validation_str = partner_code+'&'+time_stamp+'&'+nonce_str+'&'+credential_code;
  var cipher = crypto.createHash('sha256');
  cipher.update(validation_str);
  var sign = cipher.digest('hex').toLowerCase();
  console.log('generate sign:',sign);
  return sign;
}

module.exports = {
  create_jsapi_order: function (order_id, order_title, price, currency, openid, call) {
    var time_stamp = moment().format('x');
    var sign = generate_sign(time_stamp);
    console.log('sign is:',sign);
    var uri = 'https://mpay.royalpay.com.au/api/v1.0/wechat_jsapi_gateway/partners/'+partner_code+'/orders/'+order_id+'?time='+time_stamp+'&nonce_str='+nonce_str+'&sign='+sign;
    var reqBody = {
      description: order_title,
      price: price,
      currency: currency,
      notify_url: 'http://www.auewecanberra.com/payment/callback/'+order_id,
      operator: openid
    };
    request({
      url: uri,
      method: 'PUT',
      json: true,
      headers: {
        'Content-Type': 'application/json'
      },
      body: reqBody
    }, function (err, resp, body) {
      if (!err) return call(body);
    })
  },

  create_payment_uri: function (pay_url, call) {
    var redirect_uri = 'http://www.auewecanberra.com/';
    var time_stamp = moment().format('x');
    var sign = generate_sign(time_stamp);
    var payment_uri = pay_url+'?redirect='+redirect_uri+'&directpay=false'+'&time='+time_stamp+'&nonce_str='+nonce_str+'&sign='+sign;
    return call(payment_uri);
  },

  //获取汇率接口
  get_current_ex: function (call) {
    var time_stamp = moment().format('x');
    var sign = generate_sign(time_stamp);
    var ex_uri = 'https://mpay.royalpay.com.au/api/v1.0/gateway/partners/'+partner_code+'/exchange_rate?time='+time_stamp+'&nonce_str='+nonce_str+'&sign='+sign;
    request(ex_uri, function (err, resp, body) {
      if (err) return call(err);
      var rate = Number(JSON.parse(body).rate).toFixed(2);
      return call(rate);
    })
  }
}
